/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.cryptography.providers;

import io.iec.edp.caf.commons.cryptography.service.SymmetricCryptoProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * DES加密服务实现
 *
 * @author guowenchang
 */
public class AESCryptoProvider implements SymmetricCryptoProvider {

    @Override
    public byte[] encrypt(byte[] byteIn, byte[] key, byte[] vector) {
        try {
            SecretKeySpec aesSecretKeySpec = new SecretKeySpec(key, "AES");
            //Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

            //用密匙初始化Cipher对象,ENCRYPT_MODE用于将 Cipher 初始化为加密模式的常量
            cipher.init(Cipher.ENCRYPT_MODE, aesSecretKeySpec, new IvParameterSpec(vector));
            //正式执行加密操作
            return cipher.doFinal(byteIn); //按单部分操作加密或解密数据，或者结束一个多部分操作
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public byte[] decrypt(byte[] byteIn, byte[] key, byte[] vector) {
        try {
            SecretKeySpec aesSecretKeySpec = new SecretKeySpec(key, "AES");
            // Cipher对象实际完成解密操作
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.DECRYPT_MODE, aesSecretKeySpec, new IvParameterSpec(vector));
            // 真正开始解密操作
            return cipher.doFinal(byteIn);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
